package com.application.lucky.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.application.lucky.R;
import com.application.lucky.adapter.AddFriendsAdapter;
import com.application.lucky.adapter.NewFriendsAdapter;
import com.application.lucky.bean.UserBean;
import com.application.lucky.config.errorcode.UserErrorCode;
import com.application.lucky.request.CallBackEx;
import com.application.lucky.request.UserRequest;
import com.application.lucky.utils.ConnUtil;
import com.application.lucky.utils.Flog;
import com.application.lucky.widget.TitlebarView;
import com.application.lucky.widget.dialog.VerificationFriendDialog;
import com.application.mylibrary.base.BaseActivity;
import com.application.mylibrary.utils.ToastUtils;
import com.baselib.libnetwork.net.libnetworkcomponent.BaseResponse;
import com.baselib.libnetwork.net.libnetworkcomponent.HttpCallback;
import com.baselib.libnetwork.net.model.ResultResponse;
import com.qunar.im.ui.view.bigimageview.tool.utility.ui.ToastUtil;
import com.qunar.im.ui.view.recyclerview.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;

public class AddFriendsActivity extends BaseActivity implements View.OnClickListener {
    private LinearLayout mLl;
    private TitlebarView mTitleBar;
    private PublishSubject<String> mPublishSubject;
    private DisposableObserver<List<UserBean>> mDisposableObserver;
    private CompositeDisposable mCompositeDisposable;
    private EditText mEtHomeSearch;
    private TextView mTvHomeSearchCancel;
    private ImageView mIvHomeSearchDelete;
    private RecyclerView mRclView;
    private AddFriendsAdapter adapter;
    private VerificationFriendDialog dialog;
    private View layout_empty;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initListener();
    }

    private void initListener() {
        mTitleBar.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {
                finishAnim();
            }

            @Override
            public void rightClick() {

            }
        });
        mIvHomeSearchDelete.setOnClickListener(this);
        mTvHomeSearchCancel.setOnClickListener(this);
        mEtHomeSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {


            }
        });

        mEtHomeSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {

                    String s = mEtHomeSearch.getText().toString();
                    if (s.length() > 0) {
                        mIvHomeSearchDelete.setVisibility(View.VISIBLE);
                    } else {
                        adapter.setNewData(new ArrayList<UserBean>());
                        mIvHomeSearchDelete.setVisibility(View.GONE);
                    }
                    mPublishSubject.onNext(s);
                    return true;
                }
                return false;
            }
        });

        mPublishSubject = PublishSubject.create();
        mDisposableObserver = new DisposableObserver<List<UserBean>>() {

            @Override
            public void onNext(List<UserBean> s) {
                adapter.setNewData(s);
            }

            @Override
            public void onError(Throwable throwable) {

            }

            @Override
            public void onComplete() {

            }
        };
        mPublishSubject.debounce(1000, TimeUnit.MILLISECONDS).filter(new Predicate<String>() {

            @Override
            public boolean test(String s) throws Exception {

                return s.length() > 0;
            }

        }).switchMap(new Function<String, ObservableSource<List<UserBean>>>() {

            @Override
            public ObservableSource<List<UserBean>> apply(String query) throws Exception {
                return getSearchObservable(query);
            }

        }).observeOn(AndroidSchedulers.mainThread()).subscribe(mDisposableObserver);
        mCompositeDisposable = new CompositeDisposable();
        mCompositeDisposable.add(mDisposableObserver);
        layout_empty = findViewById(R.id.layout_empty);
        layout_empty.setVisibility(View.GONE);
    }

    private Observable<List<UserBean>> getSearchObservable(final String query) {
        return Observable.create(new ObservableOnSubscribe<List<UserBean>>() {

            @Override
            public void subscribe(final ObservableEmitter<List<UserBean>> observableEmitter) throws Exception {

                Log.d("SearchActivity", "开始请求，关键词为：" + query);
                new UserRequest().user_search(query, new CallBackEx<BaseResponse<UserBean>>() {
                    @Override
                    public void onSuccess(BaseResponse<UserBean> userBeanBaseResponse) {
                        List<UserBean> list = new ArrayList<>();
                        UserBean dataInfo = userBeanBaseResponse.dataInfo;
                        if (dataInfo != null) {
                            list.add(userBeanBaseResponse.dataInfo);
                        }

                        observableEmitter.onNext(list);
                        observableEmitter.onComplete();

                        if (ConnUtil.isEmpty(list)) {
                            mRclView.setVisibility(View.GONE);
                            layout_empty.setVisibility(View.VISIBLE);
                        } else {
                            mRclView.setVisibility(View.VISIBLE);
                            layout_empty.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    protected void OnFailureNeedData(int code, BaseResponse<UserBean> userBeanBaseResponse) {
                        if (code == UserErrorCode.USER_NO_EXISTS_ERROR) {
                            mRclView.setVisibility(View.GONE);
                            layout_empty.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public void onFailed(int code) {
                        if (code == UserErrorCode.USER_NO_EXISTS_ERROR) {
                            mRclView.setVisibility(View.GONE);
                            layout_empty.setVisibility(View.VISIBLE);
                        }
                    }

                });

            }
        }).subscribeOn(Schedulers.io());
    }

    private void initView() {
        mLl = findViewById(R.id.ll);
        mTitleBar = findViewById(R.id.title_bar);
        mEtHomeSearch = findViewById(R.id.et_home_search);
        mTvHomeSearchCancel = findViewById(R.id.tv_home_search_cancel);
        mIvHomeSearchDelete = findViewById(R.id.iv_home_search_delete);
        mRclView = findViewById(R.id.rcl_view);
        mRclView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new AddFriendsAdapter(R.layout.item_add_friends_layout);
        mRclView.setAdapter(adapter);
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                UserBean o = (UserBean) adapter.getData().get(position);
                if (dialog == null) {
                    dialog = new VerificationFriendDialog(AddFriendsActivity.this, true);
                    dialog.setListener(new VerificationFriendDialog.AddListener() {
                        @Override
                        public void success(String id) {
                            if (isFinishing()) {
                                return;
                            }
                            dialog.dismiss();
                            AddFriendsActivity.this.adapter.upDataItemById(id);
                        }

                        @Override
                        public void fail(String uid, int code) {
                            if (isFinishing()) {
                                return;
                            }
                            if (code == 30005) {
                                AddFriendsActivity.this.adapter.upDataItemById(uid);
                            }
                            dialog.dismiss();
                        }
                    });
                }
                dialog.setUserId(o.getUserId() + "");
                dialog.showDialog();
            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                UserBean o = (UserBean) adapter.getData().get(position);
                UserCenterActivity.jump(AddFriendsActivity.this, o.getUserId() + "", o.getNickName());
            }
        });
    }

    @Override
    public void beforeInit() {

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_friends;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_home_search_cancel:
                finishAnim();
                break;
            case R.id.iv_home_search_delete:
                if (mEtHomeSearch != null) {
                    mEtHomeSearch.setText("");

                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
        }
    }
}
